<?php
use TbfProtocol\Response;
use TbfProtocol\ProtocolProvider;
class TbfProtocol {
    static function asPage(){
        self::setProvider(\TbfProtocol\PageProtocol::obj());
    }
    static function asAction(){
        self::setProvider(\TbfProtocol\ActionProtocol::obj());
    }
    static function asApi(){
        self::setProvider(\TbfProtocol\ApiProtocol::obj());
    }
    /** @var ProtocolProvider  */
    private static $provider = null;

    /**
     * @return ProtocolProvider
     * @throws Exception
     */
    private static function getProtocolProvider(){
        if (self::$provider===null){
            self::asPage();
        }
        return self::$provider;
    }
    public static $isMockView = false;
    private static function setProvider(ProtocolProvider $provider){
        if (self::$isMockView){
            self::$provider = \TbfProtocol\SingleThreadTestProtocol::obj();
            self::$provider->processRequest();
            return;
        }
        self::$provider = $provider;
        self::$provider->processRequest();
    }
    static function clientError($msg,$http_code){
        $response = new Response();
        $response->type = Response::TYPE_CLIENT_ERROR;
        $response->msg = $msg;
        $response->http_code = $http_code;
        self::getProtocolProvider()->processResponse($response);
    }
    static function innerError($msg){
        $response = new Response();
        $response->type = Response::TYPE_INNER_ERROR;
        $response->msg = $msg;
        $response->http_code = 500;
        self::getProtocolProvider()->processResponse($response);
    }
    static function template($tplName,$d=array()){
        $response = new Response();
        $response->type = Response::TYPE_TEMPLATE;
        $response->tplName = $tplName;
        $response->data = $d;
        self::getProtocolProvider()->processResponse($response);
    }
    static function outputData($data){
        $response = new Response();
        $response->type = Response::TYPE_DATA;
        $response->data = $data;
        self::getProtocolProvider()->processResponse($response);
    }
    static function redirect($url){
        $response = new Response();
        $response->type = Response::TYPE_REDIRECT;
        $response->url = $url;
        self::getProtocolProvider()->processResponse($response);
    }
}